import 'package:flutter/material.dart';
import 'package:fsharing/core/models/store_product_query.dart';
import 'package:fsharing/core/viewmodels/pages/store/store_model.dart';
import 'package:fsharing/core/viewmodels/pages/store/store_product_query_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/widgets/product_item.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class StoreAreaPage extends StatelessWidget {
  final int storeId;
  final int storeAreaId;

  StoreAreaPage({
    Key key,
    @required this.storeId,
    @required this.storeAreaId,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<StoreModel, StoreProductQueryModel>(
      create: (context) => StoreProductQueryModel(
        Provider.of(context, listen: false),
        storeId,
        storeAreaId,
      ),
      update: (context, storeModel, model) => model..categoryId = storeModel.category?.id,
      child: Consumer<StoreProductQueryModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget(
                list: model.list,
                storeProductQuery: model.storeProductQuery,
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();
  final List<Product> list;
  final StoreProductQuery storeProductQuery;

  _SuccessWidget({
    Key key,
    @required this.list,
    @required this.storeProductQuery,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.builder(
        itemBuilder: (context, index) {
          return ProductItem(
            product: list[index],
          );
        },
        itemCount: list.length,
      ),
      enablePullDown: false,
      enablePullUp: storeProductQuery.productList.length == 10,
      onLoading: () => _onLoadData(context),
    );
  }

  void _onLoadData(BuildContext context) async {
    StoreProductQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}
